﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cairo;

namespace FigureDraw.Graphic
{
    public class CairoScreenGraphic : CommonGraphic
    {
        private Context c;

        public CairoScreenGraphic(System.Drawing.Graphics g)
        {
            Surface s = new Win32Surface(g.GetHdc());
            c = new Context(s); 
        }

        override public void DrawLine(double x1, double y1, double x2, double y2)
        {
            c.MoveTo(x1, y1);
            c.LineTo(x2, y2);
            c.Stroke();
        }

        override public void DrawRectangle(double x, double y, double width, double height)
        {
            c.Rectangle(x, y, width, height);
            c.Stroke();
        }

        override public void DrawEllipse(double x, double y, double width, double height)
        {
            double ratio = Math.Min(width, height) / Math.Max(width, height);

            double wScale = width >= height ? 1 : ratio;
            double hScale = height >= width ? 1 : ratio;
            PointD center = new PointD((x + width / 2) / wScale, (y + height / 2) / hScale);

            c.Scale(wScale, hScale);
            c.Arc(center.X, center.Y, Math.Max(width, height) / 2, 0, 2 * Math.PI);
            c.Scale(1 / wScale, 1 / hScale);
            c.Stroke();
        }

        public override void DrawText(string text, double size, double x, double y)
        {
            c.Color = new Color(0, 0, 0);
            c.SelectFontFace("Tahoma", FontSlant.Normal, FontWeight.Bold);
            c.SetFontSize(size);
            c.MoveTo(x, y + size);

            //TextExtents te = c.TextExtents(text);
            //c.MoveTo(size - te.Width / 2 - te.XBearing,
            //          size - te.Height / 2 - te.YBearing);
            c.ShowText(text);
        }

        public override void DrawArc(double x, double y, double width, double height, double startAngle, double sweepAngle)
        {
            height = 2 * height;

            double ratio = Math.Min(width, height) / Math.Max(width, height);

            double wScale = width >= height ? 1 : ratio;
            double hScale = height >= width ? 1 : ratio;
            PointD center = new PointD((x + width / 2) / wScale, (y + height / 2) / hScale);

            c.Scale(wScale, hScale);
            c.Arc(center.X, center.Y, Math.Max(width, height) / 2, startAngle * Math.PI / 180, (sweepAngle + startAngle) * Math.PI / 180);
            c.Scale(1 / wScale, 1 / hScale);
            c.Stroke();            
        }
    }
}
